import React, {FC, useEffect, useRef, useState} from 'react';
import {
  PlasmoCSUIProps,
  PlasmoGetInlineAnchor,
  PlasmoGetInlineAnchorList,
  PlasmoGetOverlayAnchor,
  PlasmoGetOverlayAnchorList, PlasmoWatchOverlayAnchor
} from "plasmo";
import {Button, IconButton, Textarea} from "@mui/joy";
import Icon from "~utils/icon";
// import ContentCopy from '@mui/icons-material/ContentCopy';
// import {onHighlightMouseEnterOrClick} from "~contents/hoverTools2";
import $ from "jquery";
import {decodeURIWrapper} from "~utils/common";
import cssText from "data-text:~style.css"
import {CacheProvider} from "@emotion/react";
import createCache from "@emotion/cache";
import updateComments from "~api/highlightText/updateComments";
import remove from "~api/highlightText/remove";
import updateColor from "~api/highlightText/updateColor";
import {HIGHLIGHT_CLASS, URL_HASH_PREFIX } from '~utils/constants';
import { showCommonDialog } from '~utils/Alert';

const styleElement = document.createElement("style")

const styleCache = createCache({
  key: "plasmo-mui-cache",
  prepend: false,
  container: styleElement
})

export const getStyle = () => {
  console.log(`getStyle: ${styleElement}`);
  styleElement.textContent += cssText;
  return styleElement
};



// import {HIGHLIGHT_CLASS} from "~contents/api/highlightText/highlight";
// import {decodeURIWrapper} from "~utils/common";
// import './hoverTools.css';


// export const getOverlayAnchorList: PlasmoGetOverlayAnchorList  = async () => document.querySelectorAll(".highlighter--highlighted")
// export const getOverlayAnchor: PlasmoGetOverlayAnchor  = async () => document.querySelector("body");// 这里的变量名称
// export const watchOverlayAnchor: PlasmoWatchOverlayAnchor = (
//   updatePosition
// ) => {
//   const interval = setInterval(() => {
//     updatePosition()
//   }, 100)
//
//   // Clear the interval when unmounted
//   return () => {
//     clearInterval(interval)
//   }
// }
// export const getInlineAnchor: PlasmoGetInlineAnchor  = async () => ({
//   element: document.querySelector("body"),
//   // insertPosition: "afterbegin"
//   insertPosition: "afterend"
// })
// export const getInlineAnchorList: PlasmoGetInlineAnchorList = async () => {
//   const anchors = document.querySelectorAll(".highlighter--highlighted")
//   return Array.from(anchors).map((element) => ({
//     element,
//     insertPosition: "afterend"
//   }))
// }
export function triggerHighlightElemClick(event) {
  const targetElement = event.target; // 获取被点击元素的 ID
  console.log(`elementId: ${event.target.getAttribute("viewstate")}`);
  document.dispatchEvent(new CustomEvent('highlightElemClicked', {
    detail: {
      elem: targetElement,
      clientX: event.clientX,
    }
  }));
  // document.dispatchEvent(new CustomEvent('highlightElemClicked'));
}
function moveToolbarToHighlight(highlightEl, cursorX) { // cursorX is optional, in which case no change is made to the x position of the hover toolbar
  const boundingRect = highlightEl.getBoundingClientRect();
  console.log(`boundingRect top: ${boundingRect.top}`);
  // const hoverTool= document.querySelector('plasmo-csui').shadowRoot.getElementById("plasmo-inline")

  const hoverTool= document.querySelector('plasmo-csui').shadowRoot.getElementById("highlighter--hover-tools")
  const toolWidth = 268; // When changing this, also update the width in css #highlighter--hover-tools--container

  const hoverTop = boundingRect.top - 45;
  // const hoverTop = boundingRect.top - 45;

  // console.log(`hoverTool old: ${hoverTool.style.top}, ${hoverTool.style.left}`);
  hoverTool.style.top = `${hoverTop}px`;
  console.log(`hover top: ${hoverTop}`);
  // console.log(`hoverTool new: ${top}, ${left}`);
  let hoverLeft = null;
  if (cursorX !== undefined) {
    if (boundingRect.width < toolWidth) {
      // center the toolbar if the highlight is smaller than the toolbar
      hoverLeft = boundingRect.left + (boundingRect.width / 2) - (toolWidth / 2);
    } else if (cursorX - boundingRect.left < toolWidth / 2) {
      // If the toolbar would overflow the highlight on the left, snap it to the left of the highlight
      hoverLeft = boundingRect.left;
    } else if (boundingRect.right - cursorX < toolWidth / 2) {
      // If the toolbar would overflow the highlight on the right, snap it to the right of the highlight
      hoverLeft = boundingRect.right - toolWidth;
    } else {
      // Else, center the toolbar above the cursor
      hoverLeft = cursorX - (toolWidth / 2);
    }

    hoverTool.style.left = `${hoverLeft}px`;
  }
}
export const initializeHighlightEventListeners = (highlightElement) => {
  // highlightElement.addEventListener('mouseenter', triggerHighlightElemClick);
  highlightElement.addEventListener('click', triggerHighlightElemClick);
  // highlightElement.addEventListener('mouseleave', onHighlightMouseLeave);
}
export const removeHighlightEventListeners = (highlightElement) => {
  // highlightElement.removeEventListener('mouseenter', onHighlightMouseEnterOrClick);
  highlightElement.removeEventListener('click', triggerHighlightElemClick);
  // highlightElement.removeEventListener('mouseleave', onHighlightMouseLeave);
}
let active = false;
let currentX;
let currentY;
let initialX;
let initialY;
let xOffset = 0;
let yOffset = 0;

const HoverTools: FC<PlasmoCSUIProps> = ({anchor}) => {
  const [display, setDisplay] = useState<boolean>(false);
  const [currentHighlightElem, setCurrentHighlightElem] = useState(null);
  const [comments, setComments] = useState<string>("");


  useEffect(() => {
    if (currentHighlightElem) {
      console.log(`register: ${currentHighlightElem.innerText}`);
    }
    window.addEventListener("scroll", () => {
      if (currentHighlightElem) {
        console.log(`scroll: ${currentHighlightElem.innerText}`);
        moveToolbarToHighlight(currentHighlightElem, undefined);
      }
    });
  }, [currentHighlightElem]);

  useEffect(() => {
    const toggleDisplay = (event: CustomEvent) => {

      setCurrentHighlightElem(event.detail.elem);
      moveToolbarToHighlight(event.detail.elem, event.detail.clientX);

      const viewstate = event.detail.elem.getAttribute("viewstate");
      const [highlightId] = viewstate.split(";;").slice(0);
      const [comments] = viewstate.split(";;").slice(-1);
      setComments(decodeURIWrapper(comments));
      // setComments(event.detail.elem.innerText);
      setDisplay(true);
    };


    // div drag ==>
    function setTranslate(xPos, yPos, el) {
      el.style.transform = "translate3d(" + xPos + "px, " + yPos + "px, 0)";
    }
    const dragItem= document.querySelector('plasmo-csui').shadowRoot.getElementById("highlighter--hover-tools")
    dragItem.addEventListener('mousedown', function(e){
      initialX = e.clientX - xOffset;
      initialY = e.clientY - yOffset;

      // @ts-ignore
      if (e.target.parentNode === dragItem) {
        active = true;
      }
    }, false);
    window.addEventListener('mouseup', function(e){
      initialX = currentX;
      initialY = currentY;
      active = false;
    }, false);
    window.addEventListener('mousemove', function(e){
      if (active) {
        e.preventDefault();

        currentX = e.clientX - initialX;
        currentY = e.clientY - initialY;

        xOffset = currentX;
        yOffset = currentY;

        setTranslate(currentX, currentY, dragItem);
      }
    }, false);
    // <==

    document.addEventListener('highlightElemClicked', toggleDisplay);
    // 组件卸载时移除事件监听器
    return () => {
      document.removeEventListener('highlightElemClicked', toggleDisplay);
    };
  }, [display]); // 依赖项数组中包含 display，确保每次 display 改变时重新绑定事件

  const handleDeleteClick = (e) => {
    console.log(`handle delete...`);
    showCommonDialog({
      title: "Delete Highlight",
      content: `Are you sure to delete this highlight? You cannot undo this action.`,
      style: "danger",
      onConfirm: async () => {
        console.log("confirmed delete");
        const highlightId = currentHighlightElem.getAttribute('data-highlight-id');
        const viewstate = currentHighlightElem.getAttribute("viewstate");
        console.log(`highlightId: ${highlightId}`);
        console.log(`viewstate: ${viewstate}`);
        remove(highlightId, viewstate);
        setDisplay(false);
      },
    });
  };
  const handleCloseClick = (e) => {
    console.log(`handle close...`);
    setDisplay(false);
  }
  const handleCopyClick = (e) => {
    let viewstate = currentHighlightElem.getAttribute('viewstate');
    const [baseUrl] = window.location.href.split(URL_HASH_PREFIX).slice(0,1);
    const [comments_decoded] = viewstate.split(";;").slice(-1).map(item => decodeURIWrapper(item));
    const [highlightId] = viewstate.split(";;").slice(0,1).map(item => item.trim());
    let highlightAndComments = "";
    if (viewstate.indexOf("*ver_simple*") !== -1) {
      let [context_decoded] = viewstate.split(";;").slice(1, 2).map(item => decodeURIWrapper(item));
      context_decoded = context_decoded.replaceAll("-,", "==").replaceAll(",-", "==");
      highlightAndComments = `[▲](${baseUrl}${URL_HASH_PREFIX}${viewstate}) ${context_decoded.trimEnd("\n")}\n > ${comments_decoded.trimEnd("\n")}\n`;
    } else if (viewstate.indexOf("*ver_image*") !== -1) {
      let [imageName_decoded, imageSrc_decoded] = viewstate.split(";;").slice(1, 3).map(item => decodeURIWrapper(item));
      // highlightAndComments = `[▲](${baseUrl}${URL_HASH_PREFIX}${viewstate}) ![${imageName_decoded}](${imageSrc_decoded})\n > ${comments_decoded.trimEnd("\n")}\n`;
      if (comments_decoded.trimEnd("\n") !== "") {
        highlightAndComments = `* [@](#${highlightId}) ![${imageName_decoded}](${imageSrc_decoded})\n> ${comments_decoded.trimEnd("\n")}\n`;
      } else {
        highlightAndComments = `* [@](#${highlightId}) ![${imageName_decoded}](${imageSrc_decoded})\n`;
      }
    }
    else {
      const highlights = document.querySelectorAll(`.${HIGHLIGHT_CLASS}[data-highlight-id='${highlightId}']`);
      const previousContext = highlights[0].previousSibling + highlights[0].parentElement.previousSibling.innerText;
      const highlightText = Array.from(highlights).map(el => el.textContent).join("");
      if (comments_decoded.trimEnd("\n") !== "") {
        highlightAndComments = `* [@](#${highlightId}) ${highlightText.trimEnd("\n")}\n> ${comments_decoded.trimEnd("\n")}\n`;
      } else {
        highlightAndComments = `* [@](#${highlightId}) ${highlightText.trimEnd("\n")}\n`;
      }
    }
    highlightAndComments = highlightAndComments.replaceAll("\n\n", "\n");
    navigator.clipboard.writeText(highlightAndComments);
  }
  const handleColorChangeClick = (e) => {
    console.log(`handle color change...`);
    const highlightId = currentHighlightElem.getAttribute('data-highlight-id');
    const viewstate = currentHighlightElem.getAttribute("viewstate");
    updateColor(highlightId, viewstate, null, e.target.title);
    console.log(`color change: ${e.target.value}, viewstate: ${viewstate}`);
  };
  const handleCommentsChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
    setComments(e.target.value);
    const highlightId = currentHighlightElem.getAttribute('data-highlight-id');
    const viewstate = currentHighlightElem.getAttribute("viewstate");
    updateComments(highlightId, viewstate, e.target.value); // JM：用户输入拿value
    console.log(`update comments: ${e.target.value}, viewstate: ${viewstate}`);
    // e.target.setAttribute("viewstate", e.target.value);
    // setPartialState({
    //   shortcutCreate: Object.assign(state.shortcutCreate, {
    //     description: e.target.value,
    //   }),
    // });
  };
  const getStyleDisplay = (display: boolean): string => {
    if (display) {
      return "block";
    } else {
      return "none";
    }
  }
  return (
    <CacheProvider value={styleCache}>
      <div id="highlighter--hover-tools" style={{display: getStyleDisplay(display)}} className="flex flex-col fixed bg-gray-200 rounded-md w-[480px]">
        <div id="highlighter--hover-tools--container" className="flex flex-row relative ml-2">
          <IconButton size="sm" style={{margin: "2px 4px 2px 0px"}} title='Close' onClick={handleCloseClick}>
            <Icon.XIcon/>
          </IconButton>
          <IconButton size="sm" style={{margin: "2px 4px 2px 0px"}} title='Copy' onClick={handleCopyClick}>
            <Icon.CopyIcon/>
          </IconButton>
          <IconButton size="sm" style={{margin: "2px 4px 2px 0px"}} title='Delete' onClick={handleDeleteClick}>
            <Icon.Trash2Icon/>
          </IconButton>
          <IconButton size="sm" variant="solid" style={{backgroundColor: "yellow", border: "2px solid #5a5a5a", margin: "2px 4px 2px 0px"}} title='yellow' onClick={handleColorChangeClick}/>
          <IconButton size="sm" variant="solid" style={{backgroundColor: "green", border: "2px solid #5a5a5a", margin: "2px 4px 2px 0px"}} title='green' onClick={handleColorChangeClick}/>
          <IconButton size="sm" variant="solid" style={{backgroundColor: "blue", border: "2px solid #5a5a5a", margin: "2px 4px 2px 0px"}} title='blue' onClick={handleColorChangeClick}/>
          <IconButton size="sm" variant="solid" style={{backgroundColor: "pink", border: "2px solid #5a5a5a", margin: "2px 4px 2px 0px"}} title='pink' onClick={handleColorChangeClick}/>
          <IconButton size="sm" variant="solid" style={{backgroundColor: "black", border: "2px solid #5a5a5a", margin: "2px 4px 2px 0px"}} title='dark' onClick={handleColorChangeClick}/>
        </div>
        <div className="w-full bg-blue-200 flex flex-col justify-start items-center">
          <Textarea
            className="w-full"
            minRows="6"
            maxRows="10"
            value={comments}
            onChange={handleCommentsChange}
          />
        </div>
      </div>
    </CacheProvider>
  )
}
export default HoverTools;
